//
//  EmotionView.swift
//  表情键盘
//
//  Created by 焦林生 on 15/11/14.
//  Copyright © 2015年 焦林生. All rights reserved.
//

import UIKit

//可重用cellID
private let EmoticonViewCellID  = "EmoticonViewCellID"
//MARK: 表情键盘视图
class EmoticonView: UIView {

    //选中表情回调
    private var selectedEmotionCallBack: (emoticon: Emoticons) -> ()
    //MARK: 监听方法
   @objc private func clickItem(item: UIBarButtonItem) {
    
        print(item.tag)
    
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
    
         //滚动 collectionView
         collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    //MARK: 构造函数
    init(selectedEmoticon: (emoticon:Emoticons) -> ()){
    
        //记录闭包属性
        selectedEmotionCallBack = selectedEmoticon
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
        //滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 懒加载控件
    //collection
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonViewLayout())
    
    // MARK: - 表情布局(类中类－只允许被包含的类使用)
    private class EmoticonViewLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            let margin = (collectionView!.bounds.height - w * row) * 0.499
            
            itemSize  = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing =  0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
    
    //工具栏
    private lazy var toolbar = UIToolbar()
    
    //MARK: 表情包数组
    private lazy var packages = EmoticonViewModel.sharedViewModel.packages

}
// MARK: - 设置界面
private extension EmoticonView {

    func setupUI() {
    //1 添加控件
       addSubview(collectionView)
       addSubview(toolbar)
       //2 布局约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
            
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.top.equalTo(self.snp_top)
        }
        //准备工具栏
        prepareToolbar()
        
        //准备collectionView
        prepareCollectionView()
        
    }
    
    //准备工具栏
    private func prepareToolbar() {
        
        toolbar.tintColor = UIColor.lightGrayColor()
        //设置按钮内容
        var items = [UIBarButtonItem]()
        var index = 0
        for s in packages {
        
            items.append(UIBarButtonItem(title: s.group_name_cn, style: .Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            
            //设置弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        
        toolbar.items = items
    }

    //准备collecView
    private func prepareCollectionView() {
    collectionView.backgroundColor = UIColor.lightGrayColor()
        
        //1 注册可重用cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellID)
        
        //2 数据源
        collectionView.dataSource = self
        
        //设置代理
        collectionView.delegate = self
    }
    
    
}

//MARK: 数据源/代理
extension EmoticonView: UICollectionViewDataSource , UICollectionViewDelegate {
    //MARK 代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        //获取表情模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        
        //执行回调
        selectedEmotionCallBack(emoticon: em)
    }
    
    //MARK: 数据方法
    //多少个表情包
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
   //每个表情包有多少表情
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellID, forIndexPath: indexPath) as! EmoticonViewCell
        
       cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
}

//MARK: 表情视图cell
private class EmoticonViewCell: UICollectionViewCell {

    //表情模型
    var emoticon: Emoticons? {
    
        didSet {
           //设置UI
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: .Normal)
            
            //设置删除按钮
            if emoticon!.isRemoved {
            
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
            
        }
    }
    //MARK: 懒加载控件
    private lazy var emoticonButton: UIButton = UIButton()
    //构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        //字体大小与高度相近
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}




